﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace WiX_Standardizer.Common.Elements
{
	public class Product
	{
		public static XElement Create()
		{
			XElement product = new XElement(SettingsParser.General.GetWixNamespace() + "Product");

			string name = SettingsParser.Product.GetProductName();
			string language = SettingsParser.Product.GetLanguage();
			string version = SettingsParser.Product.GetVersion();
			string manufacturer = SettingsParser.Product.GetManufacturer();

			product.Add(new XAttribute("Name", name));
			product.Add(new XAttribute("Language", language));
			product.Add(new XAttribute("Version", version));
			product.Add(new XAttribute("Manufacturer", manufacturer));
			product.Add(new XAttribute("UpgradeCode", Guid.NewGuid().ToString()));

			return product;
		}

		public static XElement Correct(XElement startingPoint)
		{
			XElement product = startingPoint;

			string manufacturer = SettingsParser.Product.GetManufacturer();
			if (!product.Attributes("Manufacturer").Any())
				product.Add(new XAttribute("Manufacturer", manufacturer));
			else if (!product.Attribute("Manufacturer").Value.Equals(manufacturer))
				product.SetAttributeValue("Manufacturer", manufacturer);

			string name = SettingsParser.Product.GetProductName();
			if (!product.Attributes("Name").Any())
				product.Add(new XAttribute("Name", name));
			else if (!product.Attribute("Name").Value.Equals(name))
				product.SetAttributeValue("Name", name);

			if (product.Attributes("Id").Any())
				product.Attribute("Id").Remove();

			string versionNumber = SettingsParser.Product.GetVersion();
			if (!product.Attributes("Version").Any())
				product.Add(new XAttribute("Version", versionNumber));
			else if (!product.Attribute("Version").Value.Equals(versionNumber))
				product.SetAttributeValue("Version", versionNumber);

			return product;
		}
	}
}
